import {
  debounce
} from '@/utils'

export function echartsMixin({
  chartId
} = {}) {
  return {
    data() {
      return {
        chart: null
      }
    },
    methods: {
      initChart() {
        const chartDom = chartId ? document.getElementById(chartId) : this.$el
        this.chart = this.$echarts.init(chartDom)
        this.setHandleResize()
      },
      setHandleResize() {
        this.__handleResize = debounce(() => {
          this.chart.resize()
        }, 100)
        window.addEventListener('resize', this.__handleResize)
      },
      setOption(options) {
        this.chart.setOption(options)
      }
    },
    mounted() {
      this.initChart()
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.__handleResize)
      this.chart.dispose()
      this.chart = null
    }
  }
}
